<?php

namespace app\msgapi\service;

use app\msgapi\model\{CorpInfo,SecretParam, User};
use think\facade\{Cache, Db};
error_reporting(E_ERROR | E_PARSE);
class HscorpInfoService
{
    private CorpInfo $model;
    private SecretParam $secretParamModel;

    public function __construct(
        CorpInfo $model,
        SecretParam $secretParamModel
    )
    {
//        parent::__construct();
        $this->model = $model;
        $this->secretParamModel = $secretParamModel;
    }

    //企业信息
    public function huihuaCorpInfo()
    {
        $corp_info = self::getCorpInfo(env('wework.corpid'),true);
        $info = [
            '企业全称'=>$corp_info['corp_info']['corp_full_name'],
            '企业简称'=>$corp_info['corp_info']['corp_name'],
            '开通时间'=>$corp_info['corp_info']['start_date'],
            '到期时间'=>$corp_info['corp_info']['end_date'],
            '侧边栏应用地址'=>request()->domain(),
            '应用主页地址'=>request()->domain(),
            '服务器域名'=>$_SERVER['SERVER_NAME'],
            '服务器IP' => gethostbyname($_SERVER['SERVER_NAME']),
            '被监管成员' => User::where('ispermit',1)->count(),
            '磁盘总容量' => round((disk_total_space(".")/(1024*1024*1024)),2).'GB',
            '剩余空间'=>round((disk_free_space(".")/(1024*1024*1024)),2).'GB',
            '已用空间'=>round((bcsub(disk_total_space("."),disk_free_space("."))/(1024*1024*1024)),2).'GB',
            '磁盘剩余空间'=>round(((disk_free_space(".")/disk_total_space(".")) * 100),2), //百分比
        ];
        return success_json('成功',$info);
    }


    /**
     * 获取企业信息
     * @param $id
     * @param false $iscommand //是否command命令返回 默认false
     * @return mixed|\think\response\Json
     * @throws \Throwable
     */
    public static function getCorpInfo($id, $iscommand = false)
    {
        $corpinfo = Cache::remember('conf_corpinfo', function () use ($id) {
            $corpinfo_model = new CorpInfo();
            $secret_param_model = new SecretParam();
            $corp_info = $corpinfo_model->findOrEmpty($id)->toArray();
            $secret_param = $secret_param_model->where('cid', $id)->order('version desc')->findOrEmpty()->toArray();
            return ['corp_info' => $corp_info, 'secret_param' => $secret_param];
        });
        if ($iscommand == true) {
            return $corpinfo;
        }
        return success_json('成功', $corpinfo);
    }

    /**更新配置
     * @param $adminid
     * @param $ip
     * @param $id
     * @return \think\response\Json
     */
    public function corp_save($data, $id)
    {
        if (!isset($data['version']) || $data['version'] == '') {
            return error_json('版本号错误，保存失败');
        }
        Db::startTrans();
        try {
            $secret_info = $this->secretParamModel->where('version', $data['version'])->findOrEmpty()->toArray();
            if ($secret_info) {
                $this->secretParamModel->update(['public_key' => $data['public_key'],'private_key' => $data['private_key']], ['id' => $secret_info['id']]);
            } else {
                $this->secretParamModel->create(['public_key' => $data['public_key'],'private_key' => $data['private_key'], 'version' => $data['version'], 'cid' => 1, 'add_time' => date('Y-m-d H:i:s')]);
            }
            $up_data = [
                'corpid' => $data['corpid'],
                'corp_name' => $data['corp_name'],
                'corp_full_name' => $data['corp_full_name'],
                'corp_logo' => $data['corp_logo'],
                'address_book_secret' => $data['address_book_secret'],
                'customer_secret' => $data['customer_secret'],
                'msg_secret' => $data['msg_secret'],
                'agent_id' => $data['agent_id'],
                'agent_secret' => $data['agent_secret'],
                'start_date' => $data['start_date'],
                'end_date' => $data['end_date'],
                'jssdk_file' => $data['jssdk_file']
            ];
            $this->model::update($up_data, ['id' => $id]);
            HsoperateLogService::addLog(2, request()->adminid,'修改了企业密钥配置',json_encode($up_data,256));
            Db::commit();
            Cache::delete('conf_corpinfo'); //删除缓存
            return success_json('保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return error_json('保存失败，请重试' . $e->getMessage());
        }
    }

    /**生成公钥私钥
     * @return \think\response\Json
     */
    public function rsa_keys()
    {
        $ssl = openssl_pkey_new([
            'digest_alg' => 'sha256', //可以用openssl_get_md_methods() 查看支持的加密方法
            'private_key_bits' => 2048,
            'private_key_type' => OPENSSL_KEYTYPE_RSA,
        ]);
        ## 私钥
        openssl_pkey_export($ssl, $rsaPrivateKey);
        ## 公钥
        $rsaPublicKey = openssl_pkey_get_details($ssl)['key'];
        $rsaPrivateKey = preg_replace('/[\r\n]/', '', $rsaPrivateKey);
        $rsaPrivateKey = substr($rsaPrivateKey,27);
        $rsaPrivateKey = substr($rsaPrivateKey,0,-25);
        return success_json('成功',['public_key' => $rsaPublicKey, 'private_key' => $rsaPrivateKey]);
    }

}